import axios from "axios";
import jsonBig from "json-bigint";
// import { useRouter } from "vue-router";
import router from "@/router";
import { reactive } from "vue";
import { message } from "../messages.ts";
import {
  getUserToken,
  logOut,
} from "../userinfolsage.ts";
export type DataResult = {
  code?: string;
  pages?: number;
  pagesize?: number;
  current?: number;
  content?: object;
};
// 封装post方法 (无需分页调用，POST节流)
export function postReqJSON(url: string, jsondata: DataResult) {
  const code_objs = jsondata.code ?? "1000";
  const pages_objs = jsondata.pages ?? "0";
  const pagesize_objs = jsondata.pagesize ?? "0";
  const current_objs = jsondata.current ?? "0";
  const content_objs = jsondata.content ?? "";
  let objs = {
    code: code_objs,
    pages: pages_objs,
    pagesize: pagesize_objs,
    current: current_objs,
    content: content_objs,
  };
  let json_obj = JSON.stringify(objs);

  var req_code = requests.post(url, json_obj);
  return req_code;
}

let token = getUserToken();
let requests = axios.create({
  transformResponse: [
    function (data) {
      try {
        // 如果转换成功则返回转换的数据结果
        const json = jsonBig({
          storeAsString: true,
        });
        return json.parse(data);
      } catch (err) {
        // console.error(err);
        // 如果转换失败，则包装为统一数据格式并返回
        return {
          data,
        };
      }
    },
  ],
  // 配置对象
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
    "Content-Type": "application/json; charset=utf-8",
    "X-Requested-With": "XMLHttpRequest",
    Accept: "application/json",
    Authorization: token == null ? "" : "Bearer " + token,
  },
  baseURL: "/api/",
  // 代表请求时间
  timeout: 100000,
});
requests.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么，例如添加请求头
    // config.data.content.userid = userid
    token = getUserToken();
    config.headers["Authorization"] = token == null ? "" : "Bearer " + token;
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  },
);
requests.interceptors.response.use(
  async (res) => {
    var code = res.status;
    if (code == 200) {
      var resData = res.data;
      if (resData != null && resData.code != null) {
        if (resData.code == 1000) {
          return resData;
        }
        if (resData.code == 1001) {
          message(resData.content, "warning");
        }
        if (resData.code == 1003 || resData.code == 1004) {
          logOut();
          router.push("/");
          // router.beforeEach((to, from, next) => {
          //   const token = getUserToken();
          //   // Token 失效且目标是登录页，直接放行
          //   if (!token && to.path === "/") {
          //     next();
          //   } else if (!token) {
          //     next("/"); // 未登录且去其他页，强制跳登录
          //   } else {
          //     next();
          //   }
          // });
        }
        if (resData.code == 1002) {
          // 系统出错了
          router.push("/error404");
          Promise.reject(new Error("系统数据出现问题"));
        }
      } else {
        return "";
      }
    } else {
      router.push("/error404");
      Promise.reject(new Error("服务请求无法连接"));
      return Promise.reject();
    }
  },
  (error) => {
    if (error != null) {
      router.push("/error404");
      return Promise.reject();
    }
  },
);
